package com.leesche.zcsp.node.web.intecepter.web;

import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Jerry Chan
 * @version V1.0
 * @Title: node
 * @Package com.leesche.zcsp.node.web.intecepter.module
 * @Description:( PC端用户登录拦截器，验证用户是否已经登录 )
 * @date 2016年10月17日 18:10
 */
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    protected PrivilegeService privilegeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*登录验证*/
        Principal principal = privilegeService.getCurrentPrincipal();
        if (principal == null) {
            String requestType = request.getHeader("X-Requested-With");
            if ((requestType != null) && (requestType.equalsIgnoreCase("XMLHttpRequest"))) {
                response.addHeader("status", "accessDenied");
                response.sendError(403);
                return false;
            } else {
                StringBuilder sb = new StringBuilder();

                String loginpath = "/v2/login";
                //判断是否是工厂登录地址，默认是娱乐城老板登录地址
                if (request.getServletPath().toLowerCase().indexOf("factory") != -1){
                    loginpath = "/v2/factorylogin";
                }
                sb.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort()).append(request.getContextPath());
                response.sendRedirect(sb + loginpath);
                return false;
            }
        }

        /*请求鉴权*/
        /*String requestURI = request.getRequestURI().replaceFirst("/node", "");
        System.out.println("requst uri is :" + requestURI);
        for (Long useModuleid : principal.getModuleIds()) {
            Privilege privilege = privilegeService.getWebPrivileges().get(useModuleid);
            String moduleURI = privilege.getUrl().replaceFirst("..", "");

            System.out.println("user module uri is :" + moduleURI);
            *//*当前用户拥有该资源的访问权限*//*
            if (requestURI.equalsIgnoreCase(moduleURI)) {
                return true;
            }
        }*/

        /*是输出一句话?还是跳转到一个页面?*/
        /*当前用户没有访问权限*/
        /*response.addHeader("status","unauthorized");
        response.sendError(401,"当前资源未授权");*/

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

}
